package dk.mirasola.systemtraining.user.server.cron;

import com.google.appengine.api.datastore.QueryResultIterable;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import dk.mirasola.systemtraining.server.ObjectifyUtil;
import dk.mirasola.systemtraining.server.entity.BiddingSet;
import dk.mirasola.systemtraining.user.server.service.BiddingSetDataProviderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;

public class BiddingSetsCleanUpJob extends HttpServlet {
    private static final Logger logger = Logger.getLogger(BiddingSetsCleanUpJob.class.getSimpleName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("Starting biddingsets clean up");

        Objectify ofy = ObjectifyService.begin();

        Calendar cutDate = Calendar.getInstance();
        cutDate.add(Calendar.MONTH,-2);

        logger.info("Deleting all biddingsets created before "+ cutDate.getTime());

        QueryResultIterable<Key<BiddingSet>> biddingSetsKeys =
                ofy.query(BiddingSet.class)
                   .filter("created <", cutDate.getTime())
                   .fetchKeys();

        int deleteCount = 0;
        for (final Key<BiddingSet> biddingSetsKey : biddingSetsKeys) {
            ObjectifyUtil.doTransactional(new ObjectifyUtil.ObjectifyCallback<Void>() {
                @Override
                public Void doInTransaction(Objectify ofy) {
                    BiddingSetDataProviderServiceImpl.deleteBiddingSetChildren(biddingSetsKey,ofy);
                    ofy.delete(biddingSetsKey);
                    return null;
                }
            });
            deleteCount++;
        }

        logger.info("Biddingsets clean up completed and delete "+deleteCount+" biddingsets");
    }
}
